package acom.dhy.qigsaw2test

import acom.dhy.qigsaw2test.App.Companion.testCases
import acom.dhy.qigsaw2test.net.ApiUtil
import acom.dhy.qigsaw2test.net.postResult
import acom.dhy.qigsaw2test.qigsaw.DynamicFeature
import acom.dhy.qigsaw2test.qigsaw.SplitResourcesLoaderCompat
import acom.dhy.qigsaw2test.qigsaw.crossServiceShowTip
import acom.dhy.qigsaw2test.qigsaw.startActivityComponent
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.os.Bundle
import com.dhy.annotations.Component
import com.dhy.annotations.Components
import com.dhy.compatbundle.updateQigsawSplits
import com.dhy.qigsaw.splash.data.SplitInfoMd5
import com.dhy.qigsaw.splash.data.TestCase
import com.dhy.qigsaw.splash.data.TestResult
import com.dhy.xintent.gone
import com.dhy.xintent.toast
import com.dhy.xpreference.XPreferences
import com.iqiyi.android.qigsaw.core.Qigsaw
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.text.MessageFormat

@Component
class MainActivity : BaseActivity() {
    private val TAG = "DynamicFeatures"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btJava.setOnClickListener {
            startModule(DynamicFeature.JAVA)
        }
        btJava.setOnLongClickListener {
            startActivityComponent(Components.Java.JAVA_SAMPLE_ACTIVITY, true)
            true
        }
        btAssets.setOnClickListener {
            startModule(DynamicFeature.ASSETS)
        }
        btNative.setOnClickListener {
            startModule(DynamicFeature.NATIVE)
        }
        btInstallAll.setOnClickListener {
            startModule(DynamicFeature.ALL)
        }
        btUpdateSplitInfo.setOnClickListener {
            checkSplitUpdate()
        }
        btOldSplitInfo.setOnClickListener {
            toast("empty code")
        }
        btClearData.setOnClickListener {
            clearApplicationUserData()
        }
        btCrossService.setOnClickListener {
            crossServiceShowTip(this)
        }
        ApiUtil.checkAppUpdate(this)

        btTest.setOnClickListener {
            test()
        }

        if (App.AUTO_TEST_MODE) btClearData.gone()
        cbAutoTestMode.isChecked = App.AUTO_TEST_MODE
        cbAutoTestMode.setOnCheckedChangeListener { _, isChecked ->
            App.AUTO_TEST_MODE = isChecked
        }
    }

    private fun test() {
        val res = resources
        val timeStart = System.nanoTime()
        Qigsaw.onApplicationGetResources(res)
        val timeEnd = System.nanoTime()
        println(MessageFormat.format("GetResources cost: {0}, count {1}", timeEnd - timeStart, SplitResourcesLoaderCompat.count))
    }

    private fun checkSplitUpdate() {
        ApiUtil.checkSplitUpdate(this) {
            val url = it?.url
            if (url != null) {
                val setting: SplitInfoMd5 = XPreferences.get(this)
                // "http://www.qigsaw.com/acom.dhy.qigsaw2test-split-t0-v1.0-c1-330693fb43fa098b28728fdc45315a20.apk"
                if (setting.splitInfoMd5 == null || !url.endsWith(setting.splitInfoMd5 + ".apk")) {
                    setting.splitInfoMd5 = url.substring(url.lastIndexOf('-') + 1, url.length - 4)
                    downloadSplitInfo(url, setting)
                } else toast("No update found")
            } else toast("No record found")
        }
    }

    private fun downloadSplitInfo(url: String, setting: SplitInfoMd5) {
        val file = File(cacheDir, "info.json")
        ApiUtil.download(this, url, file) {
            if (it) {
                updateQigsawSplits(file)
                XPreferences.put(this, setting)
                toast("OK")
            } else toast("downloadSplitInfo failed")
        }
    }

    @SuppressLint("PrivateApi")
    fun clearApplicationUserData() {
        try {
            val observer = Class.forName("android.content.pm.IPackageDataObserver")
            val clearApp = ActivityManager::class.java.getMethod("clearApplicationUserData", String::class.java, observer)
            val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
            clearApp.invoke(am, packageName, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        if (App.AUTO_TEST_MODE) {
            if (!testCases.containsKey(TestCase.JAVA)) {
                btJava.performClick()
            } else if (!testCases.containsKey(TestCase.ASSETS)) {
                btAssets.performClick()
            } else if (!testCases.containsKey(TestCase.NATIVE)) {
                btNative.performClick()
            } else {
                val result = if (testCases.keys.containsAll(TestCase.values().toSet())) {
                    TestResult().apply { ok = true }
                } else {
                    TestResult().apply {
                        tests = testCases
                        failures = TestCase.values().toMutableList()
                        failures.removeAll(tests.keys)
                    }
                }
                ApiUtil.api.postResult(applicationContext, result)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({

                    }, {
                        it.printStackTrace()
                    })
            }
        }
    }
}